<?
/**
 * @id $Id: login.php 4 2007-05-25 12:59:37Z gamezoom $
 * @author $Author: gamezoom $
 * @version $Revision: 4 $
 * @date $Date: 2007-05-25 12:59:37 +0000 (Fri, 25 May 2007) $
 * @svn $HeadURL: http://jxcfortaobao.googlecode.com/svn/trunk/core/www/login.php $
 */

L2P::using('inc.abstractWwwModule');

class login extends abstractWwwModule
{
	function defaultEvent()
	{
		return $this->showLoginForm();
	}
	
	function showLoginForm()
	{
		$username = isset($_POST["username"]) ? substr(trim($_POST["username"]), 0, 32) : self::$visiter->username;
		self::assign("username", $username);

		return self::display("loginForm");
	}

	function authLogin()
	{
		$username = isset($_POST["username"]) ? substr(trim($_POST["username"]), 0, 32) : "";
		$password = isset($_POST["password"]) ? trim($_POST["password"]) : "";

		$errors = array();

		$len= strlen($username);
		if($len < 1){
			$errors["username"] = "username is null";
		}
		$len = strlen($password);
		if($len < 1){
			$errors["password"] = "password is null";
		}
		if(count($errors) == 0){
			$data = pdoFactory::fetch("SELECT * FROM accounts WHERE username=:username", array(":username" => $username));
			if(!$data){
				$errors["username"] = "username is unknown";
			}else{
				if($data["password"] != md5($password)){
					$errors["password"] = "password is error";
				}else{
					self::$visiter->uid = $data["uid"];
					self::$visiter->username = $data["username"];
					self::$visiter->lastloginip = $data["lastloginip"];
					self::$visiter->lastlogindate = $data["lastlogindate"];

					$this->logEvent("login", "login");

					$referer = isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "";
					if($referer == "" || stripos($referer, "?module=login") > -1){
						$referer = "?";
					}

					header("Location: {$referer}");
					exit();
				}
			}
		}
		
		self::assign("errors", $errors);
		
		return $this->showLoginForm();
	}

	function logout()
	{
		$this->logEvent("login", "logout");

		foreach($_COOKIE as $f => $v){
			if($f != "username"){
				setcookie($f, false);
			}
		}

		$referer = isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "";
		if($referer == "" || stripos($referer, "&event=logout") > -1){
			$referer = "?";
		}
		header("Location: {$referer}");
		exit();
	}
}
?>